﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;

namespace MyLibrary.Helper
{
    /// <summary>
    /// 公共助手方法
    /// </summary>
    public class MyHelper
    {
        public enum FormatterType : int
        {
            Binary = 0,
            Soap = 1
        }
        /// <summary>
        /// 拷贝数据[字节数据]
        /// </summary>
        /// <param name="source">源数据</param>
        /// <param name="dest">目标数据</param>
        /// <param name="destOffset">目标偏移量</param>
        public static void CopyData(byte[] source, byte[] dest, int destOffset)
        {
            if (source.Length > dest.Length) throw new ArgumentException("源数据的长度不能大于目标数据长度");


            for (int i = 0; i < source.Length; i++)
                dest[destOffset + 1] = source[i];
        }

        /// <summary>
        /// 拷贝数据[字节数组]
        /// </summary>
        /// <param name="source"></param>
        /// <param name="dest"></param>
        /// <param name="srcindex"></param>
        /// <param name="destoffset"></param>
        public static void CopyData(byte[] source, byte[] dest, int srcindex, int destoffset)
        {
            if (source.Length > dest.Length) throw new ArgumentException("源数据的长度不能大于目标数据长度");
            if (srcindex >= source.Length) throw new ArgumentException("源数据起始长度超过原始数据总长度");

            for (int i = srcindex; i < source.Length; i++)
                dest[destoffset + i] = source[i];
        }

        public static byte[] SerializeObject(object obj, FormatterType formatterType)
        {
            IFormatter formatter;
            if(formatterType == FormatterType.Binary)
                formatter = new BinaryFormatter();
            else
                formatter = new SoapFormatter();

            MemoryStream serializationStream = new MemoryStream();
            formatter.Serialize(serializationStream,obj);
            byte[] buffer = serializationStream.ToArray();
            serializationStream.Close();
            return buffer;
        }

        public static void SerializeObject(object obj, FormatterType formatterType, int offset, ref byte[] buff)
        {
            byte[] buffer = SerializeObject(obj, formatterType);
            CopyData(buffer, buff, offset);
        }
    }
}
